<?php
use Core\Config;
use Core\Constant;
use Core\Session\AdminSessionHelper;
use Zend\Json\Json;

$allCategory = $this->allCategory;
$allSubCategory = $this->allSubCategory;

$dishItem = $this->dishItem;

$allUnitAsArray = $this->allUnitAsArray;
array_unshift($allUnitAsArray, array('id'=>'', 'name'=>''));
$allUnitAsJson = Json::encode($allUnitAsArray);

$allCurrencyUnit = Config::getCurrencyUnit();
$tmpArr = array();
foreach ($allCurrencyUnit as $key => $val) {
    array_push($tmpArr, array('key'=>$key, 'val'=>$val));
}

$allCurrencyUnitAsJson = Json::encode($tmpArr);

$lang = AdminSessionHelper::getCurrentLang();
if($dishItem){
    $allMyMainCategory = $dishItem->getDishCategoryByGroup($lang, Constant::$CATEGORY_GROUP_DISH);
    $allMySubCategory = $dishItem->getDishCategoryByGroup($lang, Constant::$CATEGORY_GROUP_SUBDISH);
    $allPrices = $dishItem->getDishPrice();
    $allImages = $dishItem->getDishImages();
    $allTagString = $dishItem->getDishTagsAsString($lang);

    $allArticles = $dishItem->getDishArticles($lang);
}



$dishProperties = Config::getDishProperties($lang);
$dishPropertiesAsJson = Json::encode($dishProperties);

$allTags = $this->allTags;
$tagStrings = '';
foreach ($allTags as $aTag) {
    $tagStrings = ',"'.$aTag->tag.'"';
}

if(strlen($tagStrings) > 1)
    substr($tagStrings, 1);



?>


<script type="text/javascript" src="/public/js/my_plugin/adminPriceEdit.js"></script>
<link rel="stylesheet" type="text/css" href="/public/js/my_plugin/adminPriceEdit.css">

<script type="text/javascript" src="/public/js/my_plugin/adminArticleEdit.js"></script>
<link rel="stylesheet" type="text/css" href="/public/js/my_plugin/adminArticleEdit.css">

<script type="text/javascript" src="/public/js/jquery.ui.min.js"></script>
<script type="text/javascript" src="/public/js/tagit/tag-it.js"></script>
<link rel="stylesheet" type="text/css" href="/public/js/tagit/jquery.tagit.css">
<link rel="stylesheet" type="text/css" href="/public/js/tagit/tagit.ui-zendesk.css">
<style type="text/css">
    .image_ctn_item{
        width: 125px; height: 125px; background-color: #ccc; float:left;  margin: 2px; padding: 3px;
        position: relative;
    }
    .image_ctn_item img{
        max-width: 120px; max-height: 120px;
    }

    .image_ctn_item p{
        position: absolute;
        top:90px;
        display: none;
        background-color: #4c4c4c;
        width: 120px;

        padding: 5px;
    }
    .image_ctn_item:hover p{
        display: block;
        opacity: 0.9;
    }

    .image_ctn_item p a{
        font-style: italic;
        font-size: 0.9em;
        color: #fff;
    }

    .image_ctn_item p a:hover{
        font-style: normal;
    }

</style>

<div class="ad_title_ctn">
    <h2>Thêm món ăn</h2>
</div>

<div class="ad_content_ctn">
    <div class="pa_top_ctr_ctn">
        <a id="lnkSaveDishTop" class="k-button k-button-icontext" >Lưu </a>&nbsp;&nbsp;&nbsp;
        <a id="lnkSaveAndNewDishTop" class="k-button k-button-icontext" >Lưu và thêm mới</a>
    </div>

    <div class="pa_content_ctn" id="dish_info_ctn">
        <table style="width: 100%" cellspacing="12px">
            <tr>
                <td class="title">Tên(*):</td>
                <td>
                    <input id="txtName" name="txtName" style="min-width:400px"
                           value="<?php if($dishItem)echo $dishItem->getName($lang) ?>"
                           placeholder="Nhập tên, bắt buộc" class="k-textbox"
                           required validationMessage="Chưa nhập tên">
                    <span class="k-invalid-msg" data-for="txtName"></span>
                </td>
            </tr>
            <tr>
                <td class="title">Mô tả ngắn:</td>
                <td>
                    <textarea id="txtSumarize" name="txtSumarize" style="width:400px;" rows="3"  class="k-textbox"><?php if($dishItem)echo $dishItem->getDescription($lang) ?></textarea>

                </td>
            </tr>
            <tr>
                <td class="title">Nhóm chính</td>
                <td>
                    <select id="cboMainCategory" multiple="multiple" >
                        <?php
                        foreach ($allCategory as $aCategory) {
                            if($aCategory['lft'] == $aCategory['rgt'] - 1)
                                echo '  <option value="'.$aCategory["id"].'">'.$aCategory["name"].'</option>';
                        }

                        ?>
                    </select>
                </td>
            </tr>
            <tr>
                <td class="title">Nhóm phụ</td>
                <td>
                    <select id="cboSubCategory" multiple="multiple" >
                        <?php
                        foreach ($allSubCategory as $aCategory) {
                            echo '  <option value="'.$aCategory["id"].'">'.$aCategory["name"].'</option>';
                        }

                        ?>
                    </select>
                </td>
            </tr>

            <tr>
                <td class="title">Giá</td>
                <td>
                    <div id="prCtn"></div>
                </td>

            </tr>

            <tr>
                <td class="title">Active</td>
                <td>
                    <?php
                    $checked = 'cheked';
                    if($dishItem)
                        if($dishItem->active == 1)
                            $checked = 'checked';
                        else
                            $checked = '';

                    ?>
                    <input type="checkbox" id="chkActive" <?php echo $checked ?> >
                </td>
            </tr>

            <tr>
                <td class="title">Thuộc tính món ăn</td>
                <td>
                    <select id="cboProperties" multiple="multiple" style="width: 300px"></select>
                </td>

            </tr>

            <tr>
                <td class="title">Bài viết liên quan</td>
                <td>
                    <div id="articleCtn"></div>
                </td>

            </tr>
            <tr>
                <td colspan="2">
                    <div >
                        <div style="border:1px solid #CCC; padding: 10px">
                            <div>
                                <a href="javascript:getThumbImg();" >Chọn ảnh thể hiện</a>

                                <div style="background: #F8F8F8; margin: 0 auto; padding: 5px" id="imageCtn">
                                    <?php
                                    if($allImages){
                                        foreach ($allImages as $aImage) {
                                            echo '<div  class="image_ctn_item">
                                            <img  src="'.$aImage->path.'">
                                        <p><a href="javascript:void(0);">Xóa</a></p>
                                        </div>';
                                        }
                                    }
                                    echo '<div style="clear: both"></div>';

                                    ?>
                                </div>

                            </div>
                        </div>

                        <div class="clear"></div>
                    </div>
                </td>

            </tr>
            <tr>
                <td colspan="2">
                    <div>
                        <div class="head-container" style="height: 25px">
                            <div style="float: left; font-size: 1em; font-weight: bold;padding-right: 15px">Nội dung </div>
                            <a id='lnkTougleEditor' href="javascript:tougleEditor()" title="Nội dung"><i class="fa fa-edit fa-lg"></i></a>
                            <a id='lnkCloseEditor' href="javascript:closeEditor()"  style="display: none"><i class="fa fa-power-off fa-lg"></i></a>
                        </div>
                        <div class="clear"></div>
                        <div style="min-height: 150px ;border: 1px solid #CCC; background-color: #fff; padding: 0px 7px" id = "contentContainer"><?php if($dishItem)echo $dishItem->getContent($lang) ?></div>
                </td>

            </tr>
            <tr>
                <td colspan="2">
                    <div>
                        <div class="head-container" style="height: 25px">
                            <div style="float: left; font-size: 1em; font-weight: bold;padding-right: 15px">Thành phần </span>&nbsp;&nbsp;</div>
                            <a id='lnkTougleIngredientEditor' href="javascript:tougleIngredientEditor()" ><i class="fa fa-edit fa-lg"></i></a>
                            <a id='lnkCloseIngredientEditor' href="javascript:closeIngredientEditor()"  style="display: none"><i class="fa fa-power-off fa-lg"></i></a>
                        </div>
                        <div class="clear"></div>
                        <div style="min-height: 150px ;border: 1px solid #CCC; background-color: #fff; padding: 0px 7px" id = "ingredientContainer"><?php if($dishItem)echo $dishItem->getIngredient($lang) ?></div>
                </td>

            </tr>

            <tr>
                <td colspan="2">
                    <div>
                        <div class="head-container" style="height: 25px">
                            <div style="float: left; font-size: 1em; font-weight: bold;padding-right: 15px">Hướng dẫn, cách ăn </span>&nbsp;&nbsp;</div>
                            <a id='lnkTougleHowToEditor' href="javascript:tougleHowToEditor()" ><i class="fa fa-edit fa-lg"></i></a>
                            <a id='lnkCloseHowToEditor' href="javascript:closeHowToEditor()"  style="display: none"><i class="fa fa-power-off fa-lg"></i></a>
                        </div>
                        <div class="clear"></div>
                        <div style="min-height: 150px ;border: 1px solid #CCC; background-color: #fff; padding: 0px 7px" id = "howToContainer"><?php if($dishItem)echo $dishItem->getHowTo($lang) ?></div>
                </td>

            </tr>

            <tr>
                <td colspan="2">
                    <div>
                        <div class="head-container" style="height: 25px">
                            <div style="font-size: 1em; font-weight: bold;padding-right: 15px">Tag </div>
                        </div>

                        <div id = "tagContainer">
                            <input id="txtTag" value="<?php echo $allTagString ?>">
                        </div>
                </td>

            </tr>

        </table>


    </div>

    <div class="pa_bottom_ctr_ctn">
        <a id="lnkSaveDishBottom" class="k-button k-button-icontext">Lưu </a>&nbsp;&nbsp;&nbsp;
        <a id="lnkSaveAndNewDishBottom" class="k-button k-button-icontext" >Lưu và thêm mới</a>
    </div>
</div>


<script type="text/javascript">
var validator;
var id;

var allTags = [<?php echo  $tagStrings ?>]

<?php
if($dishItem)
    echo 'id = '.$dishItem->id.';';

?>
$(document).ready(function(){

    $('#txtTag').tagit({
        availableTags: allTags,
        allowSpaces: true
    });

    $('#imageCtn .image_ctn_item p a').on('click', function(){
        $(this).parents('.image_ctn_item').each(function(){
            $(this).remove();
        })
    })

    var allMyPrice = [];
    <?php
        if($allPrices)
        foreach ($allPrices as $aPrice) {
            $unit = '';
            foreach ($allUnitAsArray as $aUnit) {
                if($aUnit['id'] == $aPrice->unit_id)
                $unit=$aUnit['name'];
            }
            $tmpStr = 'allMyPrice.push({unit:"'.$unit.'", price:'.$aPrice->price.',currency_unit:"'.$aPrice->currency_unit.'"});';
            echo $tmpStr;
        }

    ?>
    $('#prCtn').adminPriceEdit({myData:allMyPrice,

        unitJson: <?php echo $allUnitAsJson ?>,
        currentUnitJson: <?php echo $allCurrencyUnitAsJson ?>});

    var allMyArticle = [];
    <?php
        if($allArticles)
        foreach ($allArticles as $aArticle) {
            $tmpStr = 'allMyArticle.push({title:"'.$aArticle->title.'", url:"'.$aArticle->url.'"});';
            echo $tmpStr;
        }

    ?>

    $('#articleCtn').adminArticleEdit({myData:allMyArticle});
    var priceEditCtrl = $('#prCtn').data('adminPriceEdit');
    var articleEditCtrl = $('#articleCtn').data('adminArticleEdit');

    var cboMainCategory = $("#cboMainCategory").kendoMultiSelect().data("kendoMultiSelect");
    var dishMainCategories = []
    <?php
        if($allMyMainCategory)
        foreach ($allMyMainCategory as $aCategory) {
            echo 'dishMainCategories.push("'.$aCategory->id.'");';
        }

    ?>
    cboMainCategory.value(dishMainCategories);
    var cboSubCategory = $("#cboSubCategory").kendoMultiSelect().data("kendoMultiSelect");
    var dishSubCategories = []
    <?php
        if($allMySubCategory)
        foreach ($allMySubCategory as $aCategory) {
            echo 'dishSubCategories.push("'.$aCategory->id.'");';
        }

    ?>
    cboSubCategory.value(dishSubCategories);

    var cboProperties = $("#cboProperties").kendoMultiSelect({
        dataTextField: "name",dataValueField: "key",
        itemTemplate: '<img style="width: 18px" src="#:data.image#">&nbsp;#: data.name #',
        dataSource: <?php echo  $dishPropertiesAsJson ?>
    }).data("kendoMultiSelect")

    var dishProperties = []
    <?php
           if($dishItem->property){
            $tmpArr = explode('$$$', $dishItem->property);
                foreach ($tmpArr as $aProperty) {
                   echo 'dishProperties.push("'.$aProperty.'");';
               }
           }

       ?>
    cboProperties.value(dishProperties);

    validator = $("#dish_info_ctn").kendoValidator().data("kendoValidator");

    $('#lnkSaveDishBottom').click(function(){
        saveDish(function(){
            window.location = '/admin/dish';
        });
    })
    $('#lnkSaveDishTop').click(function(){
        saveDish(function(){
            window.location = '/admin/dish';
        });
    })

    $('#lnkSaveAndNewDishBottom').click(function(){
        saveDish(function(){
            resetAll();
        });
    })
    $('#lnkSaveAndNewDishTop').click(function(){
        saveDish(function(){
            resetAll();
        });
    })

    function resetAll(){
        dishName = $('#txtName').val();
        $('#txtName').val('');
        $('#txtSumarize').val('');
        $('#choseSubCategoryValue').html('');
        $('#chkActive').attr('checked', true);
        $('#imgThumb').attr('src', '');

        if ( editor )
            editor.destroy();
        $("#contentContainer").html('');
        window.scrollTo(0, 0);
        $('#txtName').focus();

        $('#error_ctn').addClass('blue_text').html("Thêm mới món ăn '"+dishName +"' thành công!");
    }

    function saveDish(successFunction){
        if(!validate())
            return;
        $.blockUI({ message: 'Vui lòng chờ...' });
        name = $("#txtName").val();
        description = $("#txtSumarize").val();
        mainCategories = cboMainCategory.value();
        subCategories = cboSubCategory.value();
        priceArr = priceEditCtrl.getPrices();
        articleArr = articleEditCtrl.getArticle();

        active = $('#chkActive').is(':checked')?1:0;
        properties = cboProperties.value();

        if(editor)
            content = editor.getData();
        else
            content = $("#contentContainer").html();

        if(ingredientEditor)
            ingredient = ingredientEditor.getData();
        else
            ingredient = $("#ingredientContainer").html();

        if(howToEditor)
            howTo = howToEditor.getData();
        else
            howTo = $("#howToContainer").html();

        allTag = $("#txtTag").tagit("assignedTags");
        allImages = getImageArr();

        $.post('/admin/dish/save-dish',{id:id,
                name:name, description:description, content:content,ingredient:ingredient,
                howTo:howTo, mainCategories:mainCategories, subCategories:subCategories,
                priceArr:priceArr, properties:properties, allTag:allTag,active:active,
                articleArr:articleArr,allImages:allImages
            }
            ,function(result){
                $.unblockUI();
                if (result.success){
                    successFunction()
                }else{
                    $('#error_ctn').removeClass('blue_text').html(result.msg);
                }
            },'json');
    }

    function validate(){
        isValid = true;
//        isValid = validator.validate();

        /*if(editor)
         content = editor.getData();
         else
         content = $("#contentContainer").html();

         if(!content || content == ''){
         alert("Vui lòng nhập nội dung");
         return false;
         }
         */

        return isValid;
    }


});


function getThumbImg(){
    try{
        var finder = new CKFinder();
        finder.basePath = '/public/js/ckfinder/';	// The path for the installation of CKFinder (default = "/ckfinder/").
        finder.selectActionFunction = setThumbFile;
        finder.popup();
    }catch(err){

    }
}

function removeThumbImg(){
    $("#imgThumb").attr("src", "" );
    $("#btnRemoveThumbImg").hide();
}

function setThumbFile( fileUrl , data , allFiles )
{

    for (obj in allFiles) {
        html = '<div  class="image_ctn_item">' +
            '<img  src="'+allFiles[obj].url+'">' +
            '<p><a href="javascript:void(0);">Xóa</a></p>' +
            '</div>';
        $('#imageCtn').append(html);
    }
    $('#imageCtn').append('<div style="clear: both"></div>');

    $('#imageCtn .image_ctn_item p a').on('click', function(){
        $(this).parents('.image_ctn_item').each(function(){
            $(this).remove();
        })
    })
}

function getImageArr(){
    resultArr = [];
    $('#imageCtn .image_ctn_item img').each(function(){
        resultArr.push($(this).attr('src'))
    })
    return resultArr;
}


var editor;
var howToEditor;
var ingredientEditor;
function tougleEditor(){
    if ( editor )
        editor.destroy();
    editor = CKEDITOR.replace( "contentContainer" ,{
        filebrowserBrowseUrl : '/public/js/ckfinder/ckfinder.html',
        filebrowserImageBrowseUrl : '/public/js/ckfinder/ckfinder.html?Type=Images',
        filebrowserFlashBrowseUrl : '/public/js/ckfinder/ckfinder.html?Type=Flash',
        filebrowserUploadUrl : '/public/js/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files',
        filebrowserImageUploadUrl : '/public/js/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images',
        filebrowserFlashUploadUrl : '/public/js/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash',
        customConfig : '/public/js/ckeditor/my_config.js',
        language: 'vi'
    });
    $('#lnkTougleEditor').hide()
    $('#lnkCloseEditor').show()
}

function tougleIngredientEditor(){
    if ( ingredientEditor )
        ingredientEditor.destroy();
    ingredientEditor = CKEDITOR.replace( "ingredientContainer" ,{
        filebrowserBrowseUrl : '/public/js/ckfinder/ckfinder.html',
        filebrowserImageBrowseUrl : '/public/js/ckfinder/ckfinder.html?Type=Images',
        filebrowserFlashBrowseUrl : '/public/js/ckfinder/ckfinder.html?Type=Flash',
        filebrowserUploadUrl : '/public/js/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files',
        filebrowserImageUploadUrl : '/public/js/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images',
        filebrowserFlashUploadUrl : '/public/js/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash',
        customConfig : '/public/js/ckeditor/my_config.js',
        language: 'vi'
    });
    $('#lnkTougleIngredientEditor').hide()
    $('#lnkCloseIngredientEditor').show()
}

function tougleHowToEditor(){
    if ( howToEditor )
        howToEditor.destroy();
    howToEditor = CKEDITOR.replace( "howToContainer" ,{
        filebrowserBrowseUrl : '/public/js/ckfinder/ckfinder.html',
        filebrowserImageBrowseUrl : '/public/js/ckfinder/ckfinder.html?Type=Images',
        filebrowserFlashBrowseUrl : '/public/js/ckfinder/ckfinder.html?Type=Flash',
        filebrowserUploadUrl : '/public/js/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files',
        filebrowserImageUploadUrl : '/public/js/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images',
        filebrowserFlashUploadUrl : '/public/js/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash',
        customConfig : '/public/js/ckeditor/my_config.js',
        language: 'vi'
    });
    $('#lnkTougleHowToEditor').hide()
    $('#lnkCloseHowToEditor').show()
}



function closeEditor(){
    editor.destroy();
    $('#lnkTougleEditor').show()
    $('#lnkCloseEditor').hide()
}

function closeIngredientEditor(){
    ingredientEditor.destroy();
    $('#lnkTougleIngredientEditor').show()
    $('#lnkCloseIngredientEditor').hide()
}

function closeHowToEditor(){
    howToEditor.destroy();
    $('#lnkTougleHowToEditor').show()
    $('#lnkCloseHowToEditor').hide()
}

</script>
